$(function () {
    var test = true;

////////////////////////////////////////////////////////////////////////////
    // this is the detailed diagnose model;
    // this model contains all data for a detailed diagnose
    // create a stand view for this model to show data.
    // also, the view should be able to modify the data in this model
    DR = {};

    DR.STATUS = {
        NOT_SET: "not set",
        PENDING: "等待处理",
        PROCESSING: "正在处理",
        FINISHED: "已完成"
    };

    DR.GENDER = {
        MALE: "男",
        FEMALE: "女",
        NOT_SET: "not set"
    };

    DR.LEFT_OR_RIGHTEYE = {
        LEFT: "左眼",
        RIGHT: "右眼",
        NOT_SET: "not set"
    };

    var DiaDetailModel = Backbone.Model.extend({
        defaults: {
            status: DR.STATUS.NOT_SET,
            name: '',                                      // name of the patient
            gender: DR.GENDER.NOT_SET,                     // gender of the patient
            patientID: '',
            originalPicture: "img/image-not-found.png",
            leftOrRightEye: DR.LEFT_OR_RIGHTEYE.NOT_SET,
            dateOfBirth: '',                                // must be yyyy-mm-dd format
            diagnoseResult: [],
            report: ""
        },

        initialize: function () {
            console.log("Initializing DiaDetail");
        }
    });

    var DiaDetailView = Backbone.View.extend({
        diaDetailViewTpl: _.template($('#diaDetailTemplate').html()),

        getDiagnoseResultTable: function (obj) {
            console.log("Generate table");
            return '<tr><td>血管检测</td><td></td><td>1000</td><td>12.00%</td></tr>';
        },

        initialize: function () {
            this.listenTo()
        },

        render: function () {
            console.log('render in diaDetailView');
            var obj = this.model.toJSON();
            this.$el.html(this.diaDetailViewTpl(obj));
            // obj.diagnoseResult.forEach(function (item) {
            //     console.log(JSON.stringify(item))
            // })
        }
    });
    console.log("here");

    // now define the DiaDetail view
/////////////////////////////////////////////////////////////////////////////
    var NewReportView = Backbone.View.extend({
        el: $('#reports').parent().parent(),

        events: {
            "click #new-diagnose": "new_diagnose",
            "change #val_original_img_left": "loadImgFromDiskl",
            "change #val_original_img_right": "loadImgFromDiskr"
        },

        initialize: function () {
            console.log("initial");
        },

        render: function () {
            console.log("render reportView");
        },

        loadImgFromDiskl: function () {
            console.log(this);
            var file = document.getElementById('val_original_img_left').files[0];
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (imgsrc) {
                // this.setAttribute("src", imgsrc.target.result);
                document.getElementById("img-original-imgl").setAttribute("src", imgsrc.target.result);
            }
        },

        loadImgFromDiskr: function () {
            console.log(this);
            var file = document.getElementById('val_original_img_right').files[0];
            var reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = function (imgsrc) {
                // this.setAttribute("src", imgsrc.target.result);
                document.getElementById("img-original-imgr").setAttribute("src", imgsrc.target.result);
            }
        },

        new_diagnose: function () {
            console.log("adding diagnose");
            // document.getElementById("detail").scrollIntoView();
            var filel = document.getElementById('val_original_img_left').files[0];
            var filer = document.getElementById('val_original_img_right').files[0];
            // if (file == null) {
            //     alert('请先添加图片');
            //     return;
            // }
            // if (!file.type.match("image/*")) {
            //     alert('请使用图片文件');
            //     return
            // }
            // document.getElementById("show_name").value = document.getElementById("val_name").value;
            // document.getElementById("show_gender").value = document.getElementById("val_gender").value;
            // document.getElementById("show_number").value = document.getElementById("val_number").value;
            upload(filel, filer);
        }

    });

    // document.getElementById("new-diagnose").onclick = function () {
    //     console.log("fuuck");
    // };


    console.log("started");
    var reportlistView = new NewReportView;

    function upload(filel, filer) {
        var request = new XMLHttpRequest();
        var fd = new FormData();
        request.responseType = 'text';
        request.open('POST', '/new_diagnose');
        fd.append("img_left", filel);
        fd.append("img_right", filer);
        jsonObj = {
            "name": document.getElementById("val_name").value,
            "id": document.getElementById("val_number").value,
            "age": document.getElementById("val_age").value,
            "gender": document.getElementById("val_gender").value,
            "number": document.getElementById("val_number").value,
            "eyesight": document.getElementById("val_eyesight").value
        };
        fd.append("info", JSON.stringify(jsonObj));
        request.send(fd);
        request.onload = function () {
            if (request.readyState == 4) {
                resp = this.responseText;
                respJson = JSON.parse(resp);
                console.log(resp);
                // diagModel.set('diagnoseResult', respJson.Desp);
                // diagModel.set('report', respJson.PdfName);
                // diagModel.set('originalPicture', respJson.OriginalName);
                window.setTimeout(function () {
                    window.location = "/api/report/" + respJson["ID"]
                }, 1000)
            }
        }
    }

    /////////////////////////////
    var diagModel = new DiaDetailModel;
    var diaview = new DiaDetailView({
        model: diagModel,
        el: $('#mainDetailView')
    });
    diaview.render();
    diaview.listenTo(diagModel, 'change', diaview.render);
    console.log("here");

});